package com.cwj.leetcode;

/**
 * 翻转一个数的比特位
 * @author Chenwujie
 * 2021/7/10 8:52
 */

public class ReverseBits {
    public static void main(String[] args) {
        //ob1100
        //00000000000100010011110101010100
        //00010101011111000100010000000000
//        for (int i = 0; i < 9999; i++) {
//            int i1 = reverseBits(i);
//            int i2 = reverseBits2(i);
//            if(i1 != i2){
//                System.out.println("error: " + i);
//            }
//        }

        long l = System.currentTimeMillis();
        for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) {
            reverseBits(i);
        }
        long l1 = System.currentTimeMillis();
        System.out.println(l1 - l);
        for (int i = Integer.MIN_VALUE; i < Integer.MAX_VALUE; i++) {
            reverseBits2(i);
        }
        long l2 = System.currentTimeMillis();
        System.out.println(l2 - l1);
    }
    public static int reverseBits(int n){
        n = ((n & 0xffff) << 16) | (n >>> 16);
        n = ((n & 0xff00ff) << 8) | ((n & 0xff00ff00) >>> 8);
        n = ((n & 0xf0f0f0f) << 4) | ((n & 0xf0f0f0f0) >>> 4);
        n = ((n & 0x33333333) << 2) | ((n & 0xcccccccc) >>> 2);
        n = ((n & 0x55555555) << 1) | ((n & 0xaaaaaaaa) >>> 1);
        return n;
    }
    public static int reverseBits2(int n) {
        int ret = 0;
        for (int i = 0; i < 32; i++) {
            ret <<= 1;
            ret |= (n & 1);
            n >>>= 1;
        }
        return ret;
    }
}
